package com.hakgc.rent.web.listener;

import com.hakgc.rent.constant.SystemConstant;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.*;

/**
 * @author Xing.Jiejian
 * @date 2020/11/18
 */
@WebListener
public class MyListener implements ServletContextListener,
        HttpSessionListener, HttpSessionAttributeListener,
        HttpSessionActivationListener {

    // Public constructor is required by servlet spec
    public MyListener() {
    }

    // -------------------------------------------------------
    // ServletContextListener implementation
    // -------------------------------------------------------
    @Override
    public void contextInitialized(ServletContextEvent sce) {
      /* This method is called when the servlet context is
         initialized(when the Web application is deployed). 
         You can initialize servlet context related data here.
      */
        System.out.println("application start");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
      /* This method is invoked when the Servlet Context 
         (the Web application) is undeployed or 
         Application Server shuts down.
      */
        System.out.println("application destroy");
    }

    // -------------------------------------------------------
    // HttpSessionListener implementation
    // -------------------------------------------------------
    @Override
    public void sessionCreated(HttpSessionEvent se) {
        /* Session is created. */
        SystemConstant.ON_LINE_VISITOR++;
    }

    /**
     * 1.执行session.invalidate()方法
     * 2.session会话超时
     * 以上两种情况会失效
     * @param se
     */
    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        /* Session is destroyed. */
        // 移除已经登录的用户
        se.getSession().removeAttribute("currentUser");
        SystemConstant.ON_LINE_VISITOR--;
    }

    // -------------------------------------------------------
    // HttpSessionAttributeListener implementation
    // -------------------------------------------------------
    @Override
    public void attributeAdded(HttpSessionBindingEvent sbe) {
      /* This method is called when an attribute 
         is added to a session.
      */
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent sbe) {
      /* This method is called when an attribute
         is removed from a session.
      */
    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent sbe) {
      /* This method is invoked when an attribute
         is replaced in a session.
      */
    }

    /**
     * Session钝化时触发
     * @param se
     */
    @Override
    public void sessionWillPassivate(HttpSessionEvent se) {

    }

    /**
     * Session激活时触发
     * @param se
     */
    @Override
    public void sessionDidActivate(HttpSessionEvent se) {

    }
}
